package com.ljph.listener;

import java.util.HashSet;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SessionListener implements HttpSessionListener {
  private static Logger _log = LoggerFactory.getLogger(SessionListener.class);
  public static String SESSION_POOL = "SESSION_POOL";

  @Override
  public void sessionCreated(HttpSessionEvent event) {
    HttpSession session = event.getSession();
    if (session != null) {
      _log.debug("sessionCreated: " + session.getId());
    }
    ServletContext application = session.getServletContext();

    @SuppressWarnings("unchecked")
    HashSet<HttpSession> sessions = (HashSet<HttpSession>) application.getAttribute(SESSION_POOL);
    if (sessions == null) {
      sessions = new HashSet<HttpSession>();
      application.setAttribute(SESSION_POOL, sessions);
    }
    sessions.add(session);
  }

  @Override
  public void sessionDestroyed(HttpSessionEvent event) {
    _log.debug("sessionDestroyed: " + event.getSession().getId());

    HttpSession session = event.getSession();

    if (session != null) {
      ServletContext application = session.getServletContext();
      @SuppressWarnings("unchecked")
      HashSet<HttpSession> sessions = (HashSet<HttpSession>) application.getAttribute(SESSION_POOL);

      if (sessions != null) {
        sessions.remove(session);
      }
    }

  }

}
